package de.graph.document;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

public class DocumentManager {

    private static final DocumentManager instance = new DocumentManager();
    
    private final Map<Long, Document> documentMap;

    private DocumentManager() {
        this.documentMap =
            Collections.synchronizedMap(new LinkedHashMap<Long, Document>());
    }

    public static final DocumentManager getInstance() {
        return instance;
    }
    
    public synchronized void registerProperties(Document document) {
        if (document == null) {
            return;
        }
        
        documentMap.put(document.getId(), document);
    }

    public synchronized void unregisterProperties(Document document) {
        if (document == null) {
            return;
        }

        documentMap.remove(document.getId());
    }
    
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        
        builder.append("Documents:\n");
        for (Document document : documentMap.values()) {
            builder.append("document (");
            builder.append(document.getId());
            builder.append(")\n");
            for (String key : document.getPropertyKeys()) {
                Object object = document.getProperty(key);
                
                builder.append("  ");
                builder.append(key);
                builder.append("=");
                builder.append(object);
                builder.append("\n");
            }
        }

        return builder.toString();
    }
}
